/*
 * @Author: 颜礼田 2564217790@qq.com
 * @Date: 2024-08-26 10:41:26
 * @LastEditors: MrDotYan 2564217790@qq.com
 * @LastEditTime: 2024-09-26 18:29:23
 * @FilePath: /turo-repo-enterprise/apps/fuck-enterprise-admin/src/stores/modules/auth.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { defineStore } from "pinia";
import { AuthState } from "@/stores/interface";
import { fetchUserPermissionListApi } from "@/api/modules/user";
import { getFlatMenuList, getShowMenuList, getAllBreadcrumbList } from "@/utils";
import { fetchMenusTree } from "@/api/modules/menus";
import { MenusSchema } from "@/schema";
import { isArray } from "@/utils/isHelper";
import { useSocketStore } from "./socket";

export const useAuthStore = defineStore({
  id: "Midway-auth",
  state: (): AuthState => ({
    // 按钮权限列表
    authButtonList: [],
    // 菜单权限列表
    authMenuList: [],
    // 当前页面的 router name，用来做按钮权限筛选
    routeName: ""
  }),
  getters: {
    // 按钮权限列表
    authButtonListGet: state => state.authButtonList,
    // 菜单权限列表 ==> 这里的菜单没有经过任何处理
    authMenuListGet: state => state.authMenuList,
    // 菜单权限列表 ==> 左侧菜单栏渲染，需要剔除 isHide == true
    showMenuListGet: state => getShowMenuList(state.authMenuList),
    // 菜单权限列表 ==> 扁平化之后的一维数组菜单，主要用来添加动态路由
    flatMenuListGet: state => getFlatMenuList(state.authMenuList),
    // 递归处理后的所有面包屑导航列表
    breadcrumbListGet: state => getAllBreadcrumbList(state.authMenuList)
  },
  actions: {
    // Get AuthButtonList
    async getAuthButtonList(params: { id: string }) {
      const { data } = await fetchUserPermissionListApi(params);
      this.authButtonList = data;

      const socketStore = useSocketStore();
      socketStore.connectGlobalSocket();
    },
    // Get AuthMenuList
    async getAuthMenuList() {
      const { data } = await fetchMenusTree();
      this.authMenuList = handlerTree(data);
    },
    // Set RouteName
    async setRouteName(name: string) {
      this.routeName = name;
    }
  }
});

function sortTree(arr, key) {
  // 对子节点进行递归排序
  function sortChildren(nodes) {
    nodes.forEach(node => {
      if (node.children) {
        node.children.sort((a, b) => a[key] - b[key]);
        sortChildren(node.children);
      }
    });
  }

  // 对顶层节点进行排序
  arr.sort((a, b) => a[key] - b[key]);
  sortChildren(arr);
  return arr;
}

function handlerTree(arr?: Array<MenusSchema>) {
  return sortTree(
    arr?.map(ele =>
      Object.assign(ele, {
        children: isArray(ele.children) ? handlerTree(ele.children) : [],
        meta: {
          role: ele.role,
          icon: ele.icon,
          title: ele.title,
          activeMenu: ele.activeMenu,
          isLink: ele.isLink,
          isHide: ele.isHide,
          isFull: ele.isFull,
          isAffix: ele.isAffix,
          isKeepAlive: ele.isKeepAlive
        }
      })
    ),
    "sort"
  );
}
